<script lang="ts" setup>
import { Snackbar } from "@varlet/ui";
import { useAppStore } from "~/store/appStore";
import { login } from "~/api/auth";
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["update:show"]);
const AppStore = useAppStore();
const loading = ref(false);
const input = ref({
  username: undefined as string | undefined,
  password: undefined as string | undefined,
  check: false,
});
async function submit() {
  const { username, password } = input.value;
  if (!username || !password) {
    Snackbar.error("用户名或密码不能为空");
    return;
  }
  loading.value = true;
  let finger = undefined;
  if (input.value.check) {
    finger = await getFingerPrint();
  }
  try {
    const data = await login(username, password, finger);
    loading.value = false;
    const { token, expireTime } = data ?? {};
    if (!token || !expireTime) {
      Snackbar.error("登录失败");
      return;
    }
    AppStore.setToken(token, expireTime);
    Snackbar.success("登录成功");
    emit("update:show", false);
  } catch (error: any) {
    loading.value = false;
    Snackbar.error("登录失败：" + error?.message);
  }
}
</script>

<template>
  <ClientOnly>
    <var-overlay :show="props.show">
      <var-form
        ref="form"
        class="box"
        scroll-to-error="start"
        @submit="submit()"
      >
        <var-space
          direction="column"
          :size="[14, 0]"
        >
          <h2>登录</h2>

          <var-input
            variant="outlined"
            size="small"
            placeholder="请输入用户名"
            :rules="[(v) => !!v || '用户名不能为空']"
            v-model="input.username"
          >
          </var-input>
          <var-input
            variant="outlined"
            type="password"
            size="small"
            placeholder="请输入密码"
            :rules="[(v) => !!v || '密码不能为空']"
            v-model="input.password"
          >
          </var-input>
          <var-checkbox v-model="input.check">信任此设备</var-checkbox>
          <div style="display: flex; gap: 1em">
            <var-button
              style="flex: 1"
              :loading="loading"
              loading-type="wave"
              type="primary"
              native-type="submit"
              >登 录</var-button
            >
            <var-button
              style="flex: 1"
              text
              :loading="loading"
              loading-type="wave"
              type="default"
              native-type="reset"
              @click="emit('update:show', false)"
              >返 回</var-button
            >
          </div>
        </var-space>
      </var-form>
    </var-overlay>
  </ClientOnly>
</template>

<style lang="less" scoped>
.box {
  padding: 0.8em;
  display: flex;
  flex-direction: column;
  align-items: center;
  border-radius: 0.5em;
  background-color: var(--color-body);
  box-shadow: 0 0 1em 0 rgb(0 0 0 / 0.1);
}
</style>
